package com.kcwl.carrier.application.service;

import com.kcwl.carrier.application.assembler.CarrierForeignDriverAssembler;
import com.kcwl.carrier.domain.entity.*;
import com.kcwl.carrier.domain.service.*;
import com.kcwl.carrier.infrastructure.enums.CarrierInfoEnums;
import com.kcwl.carrier.infrastructure.enums.InviteStatusEnum;
import com.kcwl.carrier.interfaces.command.CarrierForeignDriverBatchCommand;
import com.kcwl.carrier.interfaces.command.CarrierForeignDriverCommand;
import com.kcwl.carrier.interfaces.dto.AppropriateVehicleDTO;
import com.kcwl.carrier.interfaces.dto.CarrierForeignDriverDetailDto;
import com.kcwl.carrier.interfaces.dto.CarrierForeignDriverDto;
import com.kcwl.carrier.interfaces.enums.VehicleInfoEnums;
import com.kcwl.carrier.interfaces.query.CarrierDriverQuery;
import com.kcwl.carrier.interfaces.query.CarrierForeignDriverQuery;
import com.kcwl.carrier.interfaces.query.CarrierListQuery;
import com.kcwl.carrier.interfaces.query.VehicleQuery;
import com.kcwl.ddd.application.constants.YesNoEnum;
import com.kcwl.ddd.domain.entity.KcPage;
import com.kcwl.ddd.infrastructure.utils.KcPageConverter;
import com.kcwl.ddd.interfaces.dto.PageInfoDTO;
import com.kcwl.framework.utils.CollectionUtil;
import com.kcwl.framework.utils.KcBeanConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @描述 外协运力
 * @创建人 zxx
 * @创建时间 2022/11/25
 * @修改人和其它信息
 */
@Service
@Slf4j
public class ForeignDriverApplicationService {

    @Autowired
    private ForeignDriverDomainService foreignDriverDomainService;
    @Autowired
    private CarrierInfoDomainService carrierInfoDomainService;
    @Autowired
    private VehicleInfoDomainService vehicleInfoDomainService;
    @Autowired
    private VehicleTrailerDomainService vehicleTrailerDomainService;
    @Autowired
    private CarrierDriverDomainService carrierDriverDomainService;

    @Transactional(rollbackFor = Exception.class)
    public Boolean addForeignDriver(CarrierForeignDriverCommand carrierForeignDriverCommand) {
        CarrierForeignDriverInfo carrierForeignDriverInfo = KcBeanConverter.toBean(carrierForeignDriverCommand, CarrierForeignDriverInfo.class);
        return foreignDriverDomainService.addForeignDriver(carrierForeignDriverInfo) > 0;
    }

    public Boolean deleteForeignDriver(Long id) {
       return foreignDriverDomainService.deleteForeignDriver(id) > 0;
    }

    public Boolean disableForeignDriver(Long id) {
        return foreignDriverDomainService.disableForeignDriver(id) > 0;
    }

    public Boolean enableForeignDriver(Long id) {
        //TODO 判断是否在运输中
        return foreignDriverDomainService.enableForeignDriver(id) > 0;
    }

    public PageInfoDTO<CarrierForeignDriverDto> getForeignDriverPage(CarrierForeignDriverQuery query) {
        CarrierForeignDriverCondition carrierForeignDriverCondition = KcBeanConverter.toBean(query, CarrierForeignDriverCondition.class);
        KcPage<CarrierForeignDriverListInfo> pageList = foreignDriverDomainService.getForeignDriverList(carrierForeignDriverCondition);
        return KcPageConverter.toPageInfoDTO(pageList,CarrierForeignDriverDto.class);
    }


    public CarrierForeignDriverDetailDto getForeignDriverDetail(CarrierForeignDriverQuery query) {
        CarrierForeignDriverCondition condition = KcBeanConverter.toBean(query, CarrierForeignDriverCondition.class);
        CarrierForeignDriverDetailInfo info = foreignDriverDomainService.getForeignDriverDetail(condition);
        if(info == null){
            return new CarrierForeignDriverDetailDto();
        }
        //扩展司机信息
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(info.getDriverId());
        //扩展车辆信息
        VehicleInfo vehicleInfo = vehicleInfoDomainService.queryById(info.getVehicleId());
        //扩展挂车信息
        VehicleTrailerInfo vehicleTrailerInfo = null;
        if(vehicleInfo != null && vehicleInfo.getTrailerId() != null){
            vehicleTrailerInfo = vehicleTrailerDomainService.getById(vehicleInfo.getTrailerId());
        }
        return CarrierForeignDriverAssembler.createCarrierForeignDriver(info,carrierInfo,vehicleInfo,vehicleTrailerInfo);
    }

    public Boolean reAddForeignDriver(Long id) {
       return foreignDriverDomainService.reAddForeignDriver(id) > 0;
    }

    public Integer batchAddForeignDriver(CarrierForeignDriverBatchCommand command) {
        String[] vIds = command.getVehicleIds().split(",");
        List<Long> vehicleIds = Arrays.stream(vIds).map(a -> Long.parseLong(a.trim())).collect(Collectors.toList());
        List<VehicleInfo> vehicleInfos = vehicleInfoDomainService.queryByIds(vehicleIds);
        vehicleInfos.forEach(a->{
            CarrierForeignDriverInfo carrierForeignDriverInfo = new CarrierForeignDriverInfo();
            carrierForeignDriverInfo.setUserId(command.getUserId());
            carrierForeignDriverInfo.setDriverId(a.getCarrierId());
            carrierForeignDriverInfo.setVehicleId(a.getId());
            carrierForeignDriverInfo.setInviteStatus(InviteStatusEnum.BE_ACCEPTED.getCode());
            carrierForeignDriverInfo.setDeleted(YesNoEnum.NAY.getValue());
            carrierForeignDriverInfo.setTransportStatus(YesNoEnum.NAY.getValue());
            carrierForeignDriverInfo.setUpdateUserId(command.getUserId());
            foreignDriverDomainService.addForeignDriver(carrierForeignDriverInfo);
        });
        return vIds.length;
    }

    /**
     * 查询运输公司下没有收纳的运力且在平台司机车辆数据都符合条件的
     * @param query
     * @return
     */
    public PageInfoDTO<AppropriateVehicleDTO> getAppropriateVehicles(CarrierForeignDriverQuery query) {
        //1、手机号，姓名查询司机的集合
        List<CarrierInfo> carrierLists = new ArrayList<>();
        if(!CollectionUtil.isEmpty(query.getDriverMobiles()) || !CollectionUtil.isEmpty(query.getDriverNames())){
            CarrierListQuery carrierQuery = new CarrierListQuery();
            carrierQuery.setMobileList(query.getDriverMobiles());
            carrierQuery.setNameList(query.getDriverNames());
            carrierQuery.setAuthenticationStatus(CarrierInfoEnums.AuthenticationStatusEnum.VERIFIED.getCode());
            carrierLists = carrierInfoDomainService.getCarrierListByParams(carrierQuery);
            if(carrierLists.isEmpty()){
                return new PageInfoDTO<>(0,query.getCurPagerNo(),query.getPageSize(),carrierLists);
            }
        }
        // 默认搜索的司机都没有加入外协
        List<Long> notAddedDriverIds = carrierLists.stream().map(CarrierInfo::getId).collect(Collectors.toList());
        //2、查询当前登录的物流公司下已经添加的外协运力有哪些
        List<Long> vehicleIds = foreignDriverDomainService.selectVehicleIdsByUserId(query.getUserId());
        //3、查询当前物流公司下自有的运力
        CarrierDriverQuery carrierDriverQuery = new CarrierDriverQuery();
        carrierDriverQuery.setUserId(query.getUserId());
        List<CarrierDriverInfo> carrierDriverInfos = carrierDriverDomainService.queryCarrierDriver(carrierDriverQuery);
        List<Long> ownDriverIds = carrierDriverInfos.stream().map(CarrierDriverInfo::getDriverId).collect(Collectors.toList());
        //3、查询车辆信息
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setPlateNumbers(query.getPlateNumbers());
        vehicleQuery.setCarrierIds(notAddedDriverIds);
        vehicleQuery.setUnCarrierIds(ownDriverIds);
        vehicleQuery.setUnVehicleIds(vehicleIds);
        vehicleQuery.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.VERIFIED.getCode());
        vehicleQuery.setIsDel(YesNoEnum.NAY.getValue());
        PageInfoDTO<AppropriateVehicleDTO> appropriateVehicles = vehicleInfoDomainService.getAppropriateVehicles(vehicleQuery);
        List<AppropriateVehicleDTO> list = appropriateVehicles.getList();
        if(list.isEmpty()){
            return appropriateVehicles;
        }
        //查询返回的司机信息
        List<Long> carrierIds = list.stream().map(AppropriateVehicleDTO::getCarrierId).collect(Collectors.toList());
        List<CarrierInfo> drivers = carrierInfoDomainService.getByIds(carrierIds);
        Map<Long, CarrierInfo> driverMap = drivers.stream().collect(Collectors.toMap(CarrierInfo::getId, Function.identity()));
        list.forEach(a->{
            a.setDriverId(a.getCarrierId());
            a.setVehicleId(a.getId());
            a.setDriverName(driverMap.get(a.getDriverId()).getName());
            a.setDriverMobile(driverMap.get(a.getDriverId()).getMobile());
            a.setAllowDrivingModel(driverMap.get(a.getDriverId()).getAllowDrivingModel());
            a.setIdcardNo(driverMap.get(a.getDriverId()).getIdcardNo());
        });
        return appropriateVehicles;
    }


}
